package day7;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;

/**
 * @author oldliu
 * @since 1.0
 */
public class VerifyPicture {
    public static void main(String[] args) throws Exception {
        //File f = new File("D:\\Documents\\桌面\\无标题.png");
        //File f = new File("D:\\Documents\\桌面\\无标题.gif");
        File f = new File("D:\\Documents\\桌面\\1111.jpg");
        FileInputStream fin = new FileInputStream(f);
        byte[] b = new byte[8];
        fin.read(b);
        fin.close();
        int ch[] = new int[8];
        for (int i = 0; i < ch.length; i++) {
            ch[i] = b[i] & 0x000000FF;
            //System.out.printf(" %X ",ch[i]);
        }

        String houzhui = f.getName().substring(f.getName().lastIndexOf('.')+1).toUpperCase();
        switch (houzhui) {
            case "JPG":
                if (ch[0] == 0XFF && ch[1] == 0XD8) {
                    System.out.println("合法的jpg文件");
                } else {
                    System.out.println("非法的jpg文件");
                }
                break;
            case "PNG": {
                int[] p = {0X89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
                boolean e = Arrays.equals(ch, p);
                if (e) {
                    System.out.println("合法的png文件");
                } else {
                    System.out.println("非法的png文件");
                }
            }
            break;
            case "GIF": {
                int[] p = {0X47, 0X49, 0X46, 0X38, 0X39, 0X61};
                int[] p3 = {0X47, 0X49, 0X46, 0X38, 0X37, 0X61};
                int[] temp = Arrays.copyOf(ch, 6);


                if (Arrays.equals(temp, p) || Arrays.equals(temp, p3)) {
                    System.out.println("合法的gif文件");
                } else {
                    System.out.println("非法的gif文件");
                }
            }
            break;
            case "BMP":
                if (ch[0] == 0x42 && ch[1] == 0x4D) {
                    System.out.println("合法的bmp文件");
                } else {
                    System.out.println("非法的bmp文件");
                }
                break;
            default:
                System.out.println(houzhui + "无法识别");
        }
    }
}
